<?php
class ToolController extends Controller
{
   public function direct(){
            if(!isset($_SESSION["userId"])){
                $this->redirect(Url::createUrl("login/index"));
            }           
        }  
                    
    public function actionIndex(){
            $this->direct();
            $this->linkCanoncical = Url::createUrl('tool/index');
            $this->metaTitle = "mTop - Mạng kiếm tiền trực tuyến.";
            $this->metaKeywords = "Bán game, Bán ứng dụng, Bán SMS Kute, Bán hotclip, Gắn kích hoạt apk, Gắn kích hoạt java ,  Kinh doanh sms";
            $this->metaDescription = "Mạng kiếm tiền online của Wapmaster - Kinh doanh SMS  Content - Kinh doanh Game và Ứng dụng.";
            $this->render("index"); 
        }
    
    public function actionParkDomain()
        {
            $this->direct();
            $this->linkCanoncical = Url::createUrl('tool/parkDomain');
            $user_id =  $_SESSION["userId"];
            $rowsDomain = ShopDomain::getDomainByUserId($user_id);
            $this->render("parkDomain",array("rowsDomain"=>$rowsDomain)); 
        }  
        
    public function actionParkDomainExc()
        {
            $this->direct(); 
            $this->linkCanoncical = Url::createUrl('tool/parkDomain');
            
            $user_id =  $_SESSION["userId"];
            $user_name = $_SESSION["username"];
            $date_create = time();
            $errors="";
            
            $domain = isset($_POST["domain"]) ? trim(strip_tags($_POST["domain"])):"";
            $domain = str_replace('www.','',$domain);
            $domain = str_replace('http://','',$domain);
            $domain = str_replace('https://','',$domain);
            $domain = rtrim($domain,'/');
            // check info
            $errors .= empty($domain) ? "<p>- Domain không được để trống.</p>" : "";
           
           if(empty($errors)){
                $data = array(
                "user_id"=>array("value"=>$user_id,"type"=>1),
                "user_name"=>array("value"=>$user_name,"type"=>2),
                "domain"=>array("value"=>$domain,"type"=>2),
                "date_create"=>array("value"=>$date_create,"type"=>1)
                );
                
                $table = "c_shop_domain";
                $result = CommonDB::insertRow($table,$data);
                $this->redirect(Url::createUrl("tool/parkDomain"));
           }else{
                $rowsDomain = ShopDomain::getDomainByUserId($user_id);
                $this->render("parkDomain",array("error"=>$errors)); 
           }
        }   
    
    public function actionAjaxAddItem(){
        $catId = isset($_POST["catId"]) ? intval($_POST["catId"]):11; 
        $dataId = isset($_POST["dataId"]) ? intval($_POST["dataId"]):0;
        $data_cat = Category::getCatInfo($catId);
       
        if(isset($_SESSION["items"][$catId.'_'.$dataId])){
            echo 0;exit;
        } 
     
        if($data_cat){
            switch($data_cat["type"]){
                case 1:
                    $data_detail = Game::getGameById($dataId);
                    if($data_detail){
                        $_SESSION["items"][$catId.'_'.$dataId] = $data_detail;
                        $_SESSION["items"][$catId.'_'.$dataId]["type"] = 1;
                    }
                    break;
                case 2:
                    $data_detail = Video::getVideoById($dataId);
                    if($data_detail){
                        $_SESSION["items"][$catId.'_'.$dataId] = $data_detail;
                        $_SESSION["items"][$catId.'_'.$dataId]["type"] = 2;
                    }
                    break;
                case 3:
                    if($dataId >0){
                        $data_detail = Album::getAlbumById($dataId);
                        if($data_detail){
                            $_SESSION["items"][$catId.'_'.$dataId] = $data_detail;
                            $_SESSION["items"][$catId.'_'.$dataId]["type"] = 3;
                        }
                    }
                    break;
            }
            echo 1;
        }else{
            $data_detail = App::getInfoApp($dataId);
            if($data_detail){
                $_SESSION["items"]['0_'.$dataId] = $data_detail;
                $_SESSION["items"]['0_'.$dataId]["categoryId"] = 0;
                $_SESSION["items"]['0_'.$dataId]["type"] = $data_detail["type"];
                echo 1;
            }else{ echo 0;}
            
        }
    }
    
    
    public function actionAjaxRemoveItem(){
        $catId = isset($_POST["catId"]) ? intval($_POST["catId"]):11; 
        $dataId = isset($_POST["dataId"]) ? intval($_POST["dataId"]):0;
        if($dataId >0){
            unset($_SESSION["items"][$catId.'_'.$dataId]);
            echo 1;
        }
    }

    public function actionChangeLayout(){
        $params["icon_w"] = isset($_POST["icon_w"]) ? $_POST["icon_w"]:"";
        $params["icon_h"] = isset($_POST["icon_h"]) ? $_POST["icon_h"]:"";
        $params["bg_color"] = isset($_POST["bg_color"]) ? $_POST["bg_color"]:"";
        $params["bg_color"] = str_replace('#','',$params["bg_color"]);
       
        $params["text_color"] = isset($_POST["text_color"]) ? $_POST["text_color"]:"";
        $params["text_color"] = str_replace('#','',$params["text_color"]);
        
        $params["intro_text_color"] = isset($_POST["intro_text_color"]) ? $_POST["intro_text_color"]:"";
        $params["intro_text_color"] = str_replace('#','',$params["intro_text_color"]);
        
        $params["link_color"] = isset($_POST["link_color"]) ? $_POST["link_color"]:"";
        $params["link_color"] = str_replace('#','',$params["link_color"]);
        
        $params["border_type"] = isset($_POST["border_type"]) ? $_POST["border_type"]:"";
        $params["border_size"] = isset($_POST["border_size"]) ? intval($_POST["border_size"]):"1";
        
        $params["border_color"] = isset($_POST["border_color"]) ? $_POST["border_color"]:"";
        $params["border_color"] = str_replace('#','',$params["border_color"]);
        
        $params["padding_size"] = isset($_POST["padding_size"]) ? intval($_POST["padding_size"]):"5";
        $layout = json_encode($params);
        $_SESSION["layout"] = $layout;
        $items = $_SESSION["items"];
        foreach($items as $key=>$value){
            $item = $value;
            break;
        }
        $this->renderPartial("tpl_display_code_tmp",
        array("item"=>$item,"type"=>$_SESSION["type_display"],"radio"=>0,"layout"=>$params));
    }
    
    public function actionEmbedStep1()
    {
        $this->direct(); 
        $this->linkCanoncical = Url::createUrl('tool/embedStep1');
        $user_id =  $_SESSION["userId"];
        $num_per_page = 9;
        $type_cat = isset($_GET["type_cat"]) ? intval($_GET["type_cat"]):1; 
        $type_data = isset($_GET["type_data"]) ? intval($_GET["type_data"]):1;
        $title_embed = isset($_POST["title_embed"]) ? Common::cleanQuery($_POST["title_embed"]):"";
        $page = isset($_GET["page"]) ? intval($_GET["page"]):1;
        $error = ""; 
       
        if(!empty($title_embed)) $_SESSION["title_embed"] = $title_embed;
        
        if(isset($_POST["submit_b1"])){
            if($title_embed ==""){
                $error .= '<p style="color: red;padding:5px;"> - Tên mã nhúng không được để trống</p>';
            }
     
            if(!isset($_SESSION["items"]) || count($_SESSION["items"]) <= 0){
                $error .= '<p style="color: red;padding:5px;"> - Chưa chọn item trong mã nhúng</p>';
            }
     
            if($error==""){
                $_SESSION["title_embed"] = $title_embed;
                $this->redirect(Url::createUrl("tool/embedStep2"));
            }
        }
        //$all_cat = Category::getAllCategory(4);
        if(isset($_GET["submit"]) && $_GET["submit"]=="delete"){               
            unset($_SESSION["items"]);
            unset($_SESSION["type_display"]);
            unset($_SESSION["title_embed"]);
            unset($_SESSION["layout"]);
            $this->redirect(Url::createUrl("tool/embedStep1"));
        }
        $router = "tool/embedStep1";
         
          
        if($type_cat <4){
            $isOnline = $type_cat <2 ?1:0;
            switch($type_data){
                case 1:  // moi nhat
                    list($data, $paging) = Game::getDataLastest( $page, $num_per_page,$router,$isOnline);
                    break;
                case 2:  //hut sms nhieu
                    list($data, $paging) = Game::getDataManySms( $page, $num_per_page,$router,$isOnline);
                    break;
                case 3:  //hot nhat
                    list($data, $paging) = Game::getDataHotest( $page, $num_per_page,$router,$isOnline);
                    break;
                case 4:  //hut card nhieu
                    list($data, $paging) = Game::getDataManyCard( $page, $num_per_page,$router,$isOnline);
                    break;
                default:
                    list($data,$paging) = array(array(),'');
            }
        }else{
            $data = App::getListAppEmbed();
            $paging = "";
        }
        
        $data_embed = EmbedData::getAllData(0,1,20);
        
        $this->render("embedStep1",  array("data_embed"=>$data_embed,"data"=>$data,"paging"=>$paging
        , "type_cat"=>$type_cat, "type_data"=>$type_data, "error"=>$error));
        
    } 
    
    
     public function actionEmbedStep2(){
        $this->direct(); 
        unset($_SESSION["layout"]);
        $error = "";
        $type_display = isset($_POST["type_display"]) ? intval($_POST["type_display"]):0;
        if(!isset($_SESSION["items"])){
            $this->redirect(Url::createUrl("tool/embedStep1"));
        }
        if(isset($_POST["submit_b2"])){
            if($type_display <=0){
                $error .= '<p style="color: red;padding:5px;">- Bạn chưa chọn kiểu hiển thị</p>';
            }
            if($error==""){
                $_SESSION["type_display"] = $type_display;
                $this->redirect(Url::createUrl("tool/embedStep3"));
            }
        }
        $this->render("embedStep2",
        array("error"=>$error));
    }   

    public function actionEmbedStep3(){
        $this->direct(); 
        $error = "";
        $params["icon_w"] = isset($_POST["icon_w"]) ? $_POST["icon_w"]:"";
        $params["icon_h"] = isset($_POST["icon_h"]) ? $_POST["icon_h"]:"";
        $params["bg_color"] = isset($_POST["bg_color"]) ? $_POST["bg_color"]:"";
        $params["bg_color"] = str_replace('#','',$params["bg_color"]);
        
        $params["text_color"] = isset($_POST["text_color"]) ? $_POST["text_color"]:"";
        $params["text_color"] = str_replace('#','',$params["text_color"]);
        
        $params["intro_text_color"] = isset($_POST["intro_text_color"]) ? $_POST["intro_text_color"]:"";
        $params["intro_text_color"] = str_replace('#','',$params["intro_text_color"]);
        
        $params["link_color"] = isset($_POST["link_color"]) ? $_POST["link_color"]:"";
        $params["link_color"] = str_replace('#','',$params["link_color"]);
        
        $params["border_type"] = isset($_POST["border_type"]) ? $_POST["border_type"]:"";
        $params["border_size"] = isset($_POST["border_size"]) ? intval($_POST["border_size"]):"";
        $params["border_size"] = $params["border_size"]."px";
        
        $params["border_color"] = isset($_POST["border_color"]) ? $_POST["border_color"]:"";
        $params["border_color"] = str_replace('#','',$params["border_color"]);
        
        $params["padding_size"] = isset($_POST["padding_size"]) ? intval($_POST["padding_size"]):"";
        $params["padding_size"] = $params["padding_size"]."px";


        if(!isset($_SESSION["items"])){
            $this->redirect(Url::createUrl("tool/embedStep1"));
        }
        
        if(isset($_POST["submit_b3"])){
            $layout = json_encode($params);
            $_SESSION["layout"] = $layout;
            $user_id   = isset($_SESSION["userId"])  ? $_SESSION["userId"]:0;
            $user_name = isset($_SESSION["username"])? $_SESSION["username"]:'';
            $data_code = array(
            "user_id"=>array("value"=>$user_id,"type"=>1),
            "title"=>array("value"=>$_SESSION["title_embed"],"type"=>2),
            "create_date"=>array("value"=>time(),"type"=>1),
            "create_user"=>array("value"=>$user_name,"type"=>2),
            );
            $embed_id = CommonDB::insertRow("c_embed_data",$data_code);
            if($embed_id >0){
                $arr_key = array("embed_id","dataId","catId","type_cat","type_display","layout","create_date","create_user");
                $items = $_SESSION["items"];
                foreach($items as $key=>$value){
                    $data_js[] = Common::sanitize_output($this->renderPartial("tpl_display_code",array("item"=>$value,"type"=>$_SESSION["type_display"],"radio"=>0,"layout"=>$params),true));
                    $arr_values[] = array($embed_id,$value["id"],$value["categoryId"],$value["type"],$_SESSION["type_display"],$_SESSION["layout"],time(),$user_name);

                }
                $result = CommonDB::insertManyRows("c_embed_data_detail",$arr_key,$arr_values);
               
                /*Common::writeFile($user_name,$embed_id,$data_js);
                $js = implode("||:||",$data_js);
                $url = "http://hayquadi.com/config/writeFile?info=";
                $info = "user_name=".$user_name."&embed_id=".$embed_id."&js=".$js."";
                
                $info = urlencode(base64_encode($info));  
                $url .= $info;
 
                $result_curl = Common::cUrl($url);*/
                
                unset($_SESSION["items"]);
                unset($_SESSION["type_display"]);
                unset($_SESSION["title_embed"]);
                unset($_SESSION["layout"]);
                $this->redirect(Url::createUrl("tool/embedDetail",array("embed_id"=>$embed_id)));
            }


        }
        $this->render("embedStep3",array("error"=>$error));
    } 
    
    
    public function actionEmbedDetail(){
        $this->direct(); 
        $embed_id = isset($_GET["embed_id"]) ? intval($_GET["embed_id"]):0; 
        $user_id   = isset($_SESSION["userId"])  ? $_SESSION["userId"]:0;
        $data_embed = EmbedData::getDataById($embed_id,$user_id);
      
        if($data_embed){
            list($type_display,$layout,$items) = EmbedData::getDataDetailByEmbedId($embed_id);
            $layout = json_decode($layout,true);
            $this->render("embedStep4",
            array(
            "items"=>$items
            ,"type_display"=>$type_display  
            ,"layout"=>$layout  
            ,"data_embed"=>$data_embed  
            )
            );
        }

    }
    
    public function actionEmbedDetailByAdmin(){
        $this->direct(); 
        $embed_id = isset($_GET["embed_id"]) ? intval($_GET["embed_id"]):0; 
        $data_embed = EmbedData::getDataById($embed_id,0);
        if($data_embed){
            list($type_display,$layout,$items) = EmbedData::getDataDetailByEmbedId($embed_id);
            $layout = json_decode($layout,true);
            $this->render("embedStep4",
            array(
            "items"=>$items
            ,"type_display"=>$type_display  
            ,"layout"=>$layout  
            ,"data_embed"=>$data_embed  
            )
            );
        }

    }
    
    public function actionEmbedByUser(){
        $this->direct(); 
        $user_id   = isset($_SESSION["userId"])  ? $_SESSION["userId"]:0;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
        $currentPage = $currentPage==0 ? 1 : $currentPage;
        $numberRecordPerPage = 15;
         
        $totalEmbed = EmbedData::countTotalEmbed($user_id);
        $numberPage =  ceil($totalEmbed / $numberRecordPerPage);
        
        $data_embed = EmbedData::getAllData($user_id,$currentPage,$numberRecordPerPage);
        $this->render("embeds",array("embeds"=>$data_embed,"numberPage"=>$numberPage,"currentPage"=>$currentPage));
    }
    
    public function actionViewEmbedUser(){
        
        $detect = new Mobile_Detect();
        $isMobile = $detect->isMobile();
        $embed_id = isset($_GET["embed_id"]) ? intval($_GET["embed_id"]):0;
        $domain = isset($_GET["domain"]) ? Common::cleanQuery($_GET["domain"]):"";        
        $user = User::getDataByUsername($domain);
        $embed = EmbedData::getDataById($embed_id,$user['id']);
      
        if($detect->isiOS()){
            $ext = "ipa";
        }elseif($detect->isAndroidOS()){
            $ext = "apk";
        }elseif($detect->isMobile()){
            $ext = "jar";
        }else{          
            $ext = "";
        }
        
        $data = array();
        if($embed && $user){
            $data = array();
            list($type_display,$layout,$item) = EmbedData::getDataDetailByEmbedId($embed_id);
            $layout = json_decode($layout,true);  
            foreach($item as $value){
               if($value["type"]==1 && $ext !=""){
                     $data_file = GameFile::getGameFileByExt($value["id"],$ext);
                     if($data_file){  
                          $data[] = $value;
                     }
                }else{
                     $data[] = $value;
                }
            }
            $this->renderPartial("embedView",array("embed"=>$embed,"user"=>$user,
            "type_display"=>$type_display,
            "layout"=>$layout,
            "data"=>$data
            ));
        }
    }
    
}  
?>
